import React from 'react';
import {
  View, Image
} from '@tarojs/components';

import bleIconNor from '@/assets/images/BluetoothIconNor.png';
import bleIconSel from '@/assets/images/BluetoothIconSel.png';

class BleIcon extends React.Component {

  timer: any = undefined;

  state = {
    index: 0,
  };

  componentDidMount() {
    if (this.props.loading) {
      this.startLoadingAnimation();
    } else {
      this.endLoadingAnimation();
    }
  }

  componentWillReceiveProps(nextProps: any) {
    if (nextProps.loading != this.props.loading) {
      if (nextProps.loading) {
        this.startLoadingAnimation();
      } else {
        this.endLoadingAnimation();
      }
    }
  }

  componentWillUnmount() {
    this.endLoadingAnimation();
  }

  startLoadingAnimation = () => {
    if (this.timer) {
      this.endLoadingAnimation();
    }

    this.timer = setInterval(() => {
      const { index } = this.state;
      this.setState({ index: (index + 1) % 2 });
    }, 500);
  }

  endLoadingAnimation = () => {
    console.log('endLoadingAnimation');
    this.setState({ index: 0 });
    clearInterval(this.timer);
  }

  render() {
    const { onClick, style, highlight, loading } = this.props;
    const { index } = this.state;
    let src = bleIconNor;
    if (highlight) {
      src = bleIconSel;
    } else {
      if (loading) {
        src = index / 2 === 0 ? bleIconSel : bleIconNor;
      }
    }
    return <Image src={src} style={{ width: 20, height: 20, ...style }} onClick={onClick} />;
  }
}

export default BleIcon;
